package com.jfinal.plugin.avtivemq;

import javax.jms.*;

/**
 * @createTime: 2018/12/20
 * @author: HingLo
 * @description: 发送消息工具方法
 */
public class SendMsgKit {

    /**
     * 发送队列消息 (队列模式点对点 被接收后消失)
     *
     * @param queueName 队列名称
     * @param message   消息类型
     * @return 返回结果
     * @throws JMSException         JMSException
     * @throws InterruptedException InterruptedException
     */
    public static boolean sendQueueMsg(String queueName, Message message) throws JMSException, InterruptedException {
        Session session = SessionKit.getJmsSession();
        return sendQueueMsg(queueName, message, session);
    }

    /***
     * 兼容接口消息
     * @param queueName 队列名称
     * @param message 消息结果
     * @param session session
     * @return 返回消息结果
     * @throws JMSException
     * @throws InterruptedException
     */
    public static boolean sendQueueMsg(String queueName, Message message, Session session) throws JMSException, InterruptedException {
        Destination destination = DestinationKit.createDestination(MessageType.QUEUE, queueName, session);
        return sendMsg(message, session, destination);
    }

    /**
     * 发送订阅消息(订阅模式，可被多人接收 消息发送后不论是否有接收者，消息都消失)
     *
     * @param queueName 队列名称
     * @param message   消息类型
     * @return 返回结果
     * @throws JMSException         JMSException
     * @throws InterruptedException InterruptedException
     */
    public static boolean sendTopicsMsg(String queueName, Message message) throws JMSException, InterruptedException {
        Session session = SessionKit.getJmsSession();
        return sendTopicsMsg(queueName, message, session);
    }

    /**
     * 发送订阅消息
     *
     * @param queueName 队列名称
     * @param message   消息类型
     * @return 返回结果
     * @throws JMSException         JMSException
     * @throws InterruptedException InterruptedException
     */
    public static boolean sendTopicsMsg(String queueName, Message message, Session session) throws JMSException, InterruptedException {
        Destination destination = DestinationKit.createDestination(MessageType.TOPICS, queueName, session);
        return sendMsg(message, session, destination);
    }

    /**
     * 发送消息
     *
     * @param message     消息
     * @param session     session
     * @param destination 目标
     * @return 返回发送结果
     * @throws JMSException 异常结果
     */
    private static boolean sendMsg(Message message, Session session, Destination destination) throws JMSException {
        MessageProducer producer = DestinationKit.createMessageProducer(session, destination);
        try {
            producer.send(message);
            // 如果是开启了事物
            if (ConnectFactory.isTransacted()) {
                session.commit();
            }
            // 发送消息结束后session进行释放
            SessionKit.closed(session);
            return true;
        } catch (JMSException e) {
            return false;
        }
    }
}
